<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>promise_principle</title>
</head>
<body>
<script>
    function Promise(fn) {
        var state = 'pending',
            value = null,
            callbacks = [];

        this.then = function (onFulfilled) {
            return new Promise(function (resolve) {
                handle({
                    onFulfilled: onFulfilled || null,
                    resolve: resolve
                });
            });
        };

        function handle(callback) {
            if (state === 'pending') {
                callbacks.push(callback);
                return;
            }
            //如果then中没有传递任何东西
            if(!callback.onResolved) {
                callback.resolve(value);
                return;
            }

            var ret = callback.onFulfilled(value);
            callback.resolve(ret);
        }


        function resolve(newValue) {
            if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
                var then = newValue.then;
                if (typeof then === 'function') {
                    then.call(newValue, resolve);
                    return;
                }
            }
            state = 'fulfilled';
            value = newValue;
            setTimeout(function () {
                callbacks.forEach(function (callback) {
                    handle(callback);
                });
            }, 0);
        }

        fn(resolve);
    }
    //例1
    function getUserId() {
        return new Promise(function(resolve) {
            //异步请求
            http.get(url, function(results) {
                resolve(results.id)
            })
        })
    }
    // 例4
   /* getUserId()
        .then(getUserJobById)
        .then(function (job) {
            // 对job的处理
        });*/

    function getUserJobById(id) {
        return new Promise(function (resolve) {
            http.get(baseUrl + id, function(job) {
                resolve(job);
            });
        });
    }


    function isIsomorphic(firstString, secondString) {

        // 检查长度是否相等，如果不相等, 它们不可能是同构的
        if (firstString.length !== secondString.length) return false

        var letterMap = {};

        for (var i = 0; i < firstString.length; i++) {
            var letterA = firstString[i],
                letterB = secondString[i];

            // 如果 letterA 不存在, 创建一个 map，并将 letterB 赋值给它
            if (letterMap[letterA] === undefined) {
                console.log(letterMap)
                letterMap[letterA] = letterB;
            } else if (letterMap[letterA] !== letterB) {
                // 如果 letterA 在 map 中已存在, 但不是与 letterB 对应，
                // 那么这意味着 letterA 与多个字符相对应。
                return false;
            }
        }
        // 迭代完毕，如果满足条件，那么返回 true。
        // 它们是同构的。
        console.log(letterMap)
        return true;
    }


    isIsomorphic("qaqa",'wswu')






</script>
</body>
</html>